import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message } from 'antd';
import axios from 'axios';
import UserCards from './UserCards';

const AdminDashboard = () => {
    const [users, setUsers] = useState([]);
    const [editVisible, setEditVisible] = useState(false);
    const [addVisible, setAddVisible] = useState(false);
    const [currentUser, setCurrentUser] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');

    const fetchUsers = async () => {
        try {
            const response = await axios.get('http://localhost:3001/users');
            setUsers(response.data);
        } catch (error) {
            message.error('Failed to fetch users');
        }
    };

    const handleEditUser = (user) => {
        setCurrentUser(user);
        setEditVisible(true);
    };

    const handleDeleteUser = async (userId) => {
        try {
            await axios.delete(`http://localhost:3001/users/${userId}`);
            message.success('User deleted');
            fetchUsers();
        } catch (error) {
            message.error('Failed to delete user');
        }
    };

    const handleSaveUser = async (values) => {
        try {
            await axios.put(`http://localhost:3001/users/${currentUser.id}`, values);
            message.success('User updated');
            fetchUsers();
            setEditVisible(false);
            setCurrentUser(null);
        } catch (error) {
            message.error('Failed to save user');
        }
    };

    const handleAddUser = async (values) => {
        try {
            await axios.post('http://localhost:3001/register', values);
            message.success('User added');
            fetchUsers();
            setAddVisible(false);
        } catch (error) {
            message.error('Failed to add user');
        }
    };

    useEffect(() => {
        fetchUsers();
    }, []);

    const handleSearch = (e) => {
        setSearchTerm(e.target.value);
    };

    const filteredUsers = users.filter(user =>
        user.username.toLowerCase().includes(searchTerm.toLowerCase())
    );

    const columns = [
        { title: 'Username', dataIndex: 'username', key: 'username' },
        { title: 'Points', dataIndex: 'points', key: 'points' },
        {
            title: 'Actions',
            render: (text, record) => (
                <span>
                    <Button onClick={() => handleEditUser(record)}>编辑用户信息</Button>
                    <Button onClick={() => handleDeleteUser(record.id)} danger>删除账户</Button>
                    <UserCards userId={record.id} />
                </span>
            ),
        },
    ];

    return (
        <div>
            <Input placeholder="Search by username" value={searchTerm} onChange={handleSearch} style={{ marginBottom: 20 }} />
            <Button type="primary" onClick={() => setAddVisible(true)}>添加用户</Button>
            <Table columns={columns} dataSource={filteredUsers} rowKey="id" />
            <Modal
                title='Edit User'
                visible={editVisible}
                onCancel={() => { setEditVisible(false); setCurrentUser(null); }}
                footer={null}
            >
                <Form onFinish={handleSaveUser} initialValues={currentUser}>
                    <Form.Item name="username" rules={[{ required: true, message: 'Please input username!' }]}>
                        <Input placeholder="Username" />
                    </Form.Item>
                    <Form.Item name="points" rules={[{ required: true, message: 'Please input points!' }]}>
                        <Input placeholder="Points" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                title='添加账户'
                visible={addVisible}
                onCancel={() => setAddVisible(false)}
                footer={null}
            >
                <Form onFinish={handleAddUser}>
                    <Form.Item name="username" rules={[{ required: true, message: 'Please input username!' }]}>
                        <Input placeholder="Username" />
                    </Form.Item>
                    <Form.Item name="password" rules={[{ required: true, message: 'Please input password!' }]}>
                        <Input.Password placeholder="Password" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default AdminDashboard;
